package org.cnbi.web.controller.manage;



import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.tools.generic.NumberTool;
import org.cnbi.entity.Menu;
import org.cnbi.entity.Role;
import org.cnbi.service.IHandleService;
import org.cnbi.service.IRightService;
import org.cnbi.service.ISystemService;
import org.cnbi.utils.json.JsonUtil;
import org.cnbi.utils.pojo.SqlParamsBean;
import org.cnbi.utils.tools.ActionConstants;
import org.cnbi.utils.tools.Constants;
import org.cnbi.utils.tools.GlobalConstants;
import org.cnbi.utils.tools.MenuConstants;
import org.cnbi.utils.tools.StateConstants;
import org.cnbi.utils.tools.UserConstants;
import org.cnbi.web.controller.base.BaseController;
import org.cnbi.web.utils.ContextHolderUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 权限控制Controller
 * Copyright © 2014中国经邦. All rights reserved.
 * @author zhh
 * @date 2014年5月6日下午11:14:04
 * @cnbi-web
 */
@Controller
@RequestMapping("/rightM")
public class RightMController extends BaseController {
	
	private static final Log logger = LogFactory.getLog(RightMController.class);
	
	public static final NumberTool numTools = new NumberTool();
	
	@Autowired
	private IHandleService handleService;
	
	@Autowired
	private ISystemService systemService;
	
	@Autowired
	private IRightService rightService;
	/**
	 * 权限管理 入口
	 * @param param 参数类
	 * @param menu 当前 菜单项
	 * @page 分页类
	 * **/
	@RequestMapping(value = "/index")
	public ModelAndView main(SqlParamsBean param,Menu menu,HttpServletResponse response) {
		ModelAndView view = getReturnView(menu,response);
		return view;
	}
	
	@RequestMapping(value = "/addRole")
	public ModelAndView addRole(SqlParamsBean param,Menu menu,Role role,HttpServletResponse response){
		//添加角色 sql
		String sql = getSqlByKey(UserConstants.ROLE+ActionConstants.ADD);
		rightService.addRole(sql, role);
		systemService.addLog(getSqlByKey(ActionConstants.MANAGE + ActionConstants.ADD+"Log"),getSysLog("角色【" + role.getSroleName()+ "】添加成功！", GlobalConstants.Log_Type_INSERT, GlobalConstants.Log_Leavel_INFO));
		ModelAndView view = getReturnView(menu,response);
		return view;
	}
	
	@RequestMapping(value = "/selectRoleAndMenus")
	@ResponseBody
	public Object selectRoleAndMenus(SqlParamsBean param,Menu menu,Role role,HttpServletResponse response){
		//查询选中的角色 所拥有的菜单权限列表  sql
		String sql = getSqlByKey(UserConstants.ROLE+ActionConstants.QUERY+MenuConstants.MENU);
		List<?> list = handleService.queryDynamicBeanList(sql, role,false);
		return list;
	}
	
	@RequestMapping(value = "/updateRole")
	public ModelAndView updateRole(SqlParamsBean param,Menu menu,Role role,HttpServletResponse response){
		//添加角色 sql
		String sql = getSqlByKey(UserConstants.ROLE+ActionConstants.UPDATE);
		rightService.editRole(sql, role);
		systemService.addLog(getSqlByKey(ActionConstants.MANAGE + ActionConstants.ADD+"Log"),getSysLog("角色【" + role.getSroleName()+ "】修改成功！", GlobalConstants.Log_Type_INSERT, GlobalConstants.Log_Leavel_INFO));
		ModelAndView view = getReturnView(menu,response);
		return view;
	}
	
	@RequestMapping(value = "/delRole")
	public ModelAndView delRole(SqlParamsBean param,Menu menu,Role role,HttpServletResponse response){
		//删除 角色 菜单 sql
		String sqlRM = getSqlByKey(UserConstants.ROLE+ActionConstants.DEL+"Permission"); 
		String sqlR = getSqlByKey(UserConstants.ROLE+ActionConstants.DEL);
	
		rightService.removeRole(sqlRM, role);
		systemService.addLog(getSqlByKey(ActionConstants.MANAGE + ActionConstants.ADD+"Log"),getSysLog("角色【" + role.getSroleName()+ " 菜单项】删除成功！", GlobalConstants.Log_Type_INSERT, GlobalConstants.Log_Leavel_INFO));
		rightService.removeRole(sqlR,role);
		systemService.addLog(getSqlByKey(ActionConstants.MANAGE + ActionConstants.ADD+"Log"),getSysLog("角色【" + role.getSroleName()+ "】删除成功！", GlobalConstants.Log_Type_INSERT, GlobalConstants.Log_Leavel_INFO));
		ModelAndView view = getReturnView(menu,response);
		return view;
	}
	
	@RequestMapping(value = "/grant")
	public ModelAndView grand(SqlParamsBean param,Menu menu,Role role,HttpServletResponse response) {
		ModelAndView view = getReturnView(menu,response);
		String roles = String.valueOf(role.getRoleID());
		String menus = ContextHolderUtils.getRequest().getParameter("menux");
		//批量插入 list
		List<Object[]> list = resetRolMenu(roles,menus);
		//权限表sql
		String sql = getSqlByKey(ActionConstants.MANAGE+ActionConstants.ADD+"Permission");
		int[] permssion = handleService.batchUpdate(sql, list);
		logger.error(permssion);
		systemService.addLog(getSqlByKey(ActionConstants.MANAGE + ActionConstants.ADD+"Log"),getSysLog("角色【" + role.getSroleName()+ "】分配菜单！", GlobalConstants.Log_Type_INSERT, GlobalConstants.Log_Leavel_INFO));
		return view;
	}
	
	/**
	 * 批量出入 对象
	 * @param roles
	 * @param menus
	 * @return list
	 * **/
	private List<Object[]> resetRolMenu(String roles, String menus) {
		List<Object[]> list = new ArrayList<Object[]>();
		if(menus.contains(",")){
			String[] menuArr = menus.split(",");
			 for (int i = 0; i < menuArr.length; i++) {
				 Object[] obj = new Object[]{roles,menuArr[i],roles,menuArr[i]};
				 list.add(obj);
			}
		}else{
			Object[] obj = new Object[]{roles,menus,roles,menus};
			list.add(obj);
		}
		return list;

	}

	/**
	 * @param menu
	 * @return view
	 * **/
	private ModelAndView getReturnView(Menu menu,HttpServletResponse response) {
		ModelAndView view = secondNavHandle(menu, response);
		view.addObject("pageBean", menu);
		setContentType(response, null);
		setContext(view);
		//角色 列表
		String sql = getSqlByKey(UserConstants.ROLE+StateConstants.LIST);
		List<Role> list = rightService.queryList(sql,new Role());
		//菜单列表树
		Menu menuTree = (Menu) ContextHolderUtils.getServletContext().getAttribute(MenuConstants.MENU+MenuConstants.TREE);
		view.addObject(Constants.ROLE+StateConstants.LIST, list);
		view.addObject(MenuConstants.MENU+MenuConstants.TREE, menuTree);
		logger.info("datas===>>>>"+JsonUtil.generateJson(menuTree));
		view.addObject("numTools", numTools);
		return view;
	}
	
}
